﻿using System.Globalization;
using System.Net;
using System.Windows;

namespace LaserAutoTest.Common
{
    public static class StringExtension
    {
       public static ExceptionInfo exceptionInfo = new ExceptionInfo();

        public static decimal ToDecimal(this string str)
        {
            decimal d = 0;
            decimal.TryParse(str, out d);
            return d;
        }

        public static int ToInt(this string str)
        {
            if (string.IsNullOrEmpty(str) || str == "N/A" || str == "ERROR")
                throw new Exception("返回值类型错误");
            int d = 0;
            int.TryParse(str, out d);
            return d;
        }

        public static decimal? ToDecimalNullable(this string str)
        {
            if (string.IsNullOrEmpty(str) || str == "N/A" || str == "ERROR")
                return null;
            else
            {
                decimal d = 0;
                if (str.Contains("E-"))
                    d = Convert.ToDecimal(decimal.Parse(str,NumberStyles.Float));
                else
                    decimal.TryParse(str, out d);
                return d;
            }
        }

        public static double ToDouble(this string str)
        {
            double d = 0;
            double.TryParse(str, out d);
            return d;
        }


        public static IPEndPoint ToIPEndPoint(this string str)
        {
            var arr = str.Split(':');
            return new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
        }

        public static string ToException(this string str)
        {
            string result = string.Empty;

            if(exceptionInfo.exceptionDic.ContainsKey(str))
                result = exceptionInfo.exceptionDic[str];
            return result;
        }
    }
}
